package com.jinglvhuanjing.app.widget;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatTextView;

import com.jinglvhuanjing.app.R;
import com.jinglvhuanjing.app.utils.ByteUtil;
import com.jinglvhuanjing.app.utils.ExecutorProcessPool;
import com.jinglvhuanjing.app.utils.LOG;
import com.jinglvhuanjing.app.utils.SingletonSerl;
import com.jinglvhuanjing.app.utils.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

public class ParamSettingTermView extends androidx.constraintlayout.widget.ConstraintLayout {
    public ParamSettingTermView(@NonNull Context context) {
        super(context);
        this.init(context);
    }

    public ParamSettingTermView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.init(context);
    }

    public ParamSettingTermView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.init(context);
    }

    private String TAG = "运行状态";

    private SingletonSerl singletonSerl;
    /*** label ***/
    private AppCompatTextView param_setting_term_label;
    /*** 参数1 ***/
    private CustomTextView param_1;
    /*** 参数2 ***/
    private CustomTextView param_2;
    /*** 参数3 ***/
    private CustomTextView param_3;
    /*** 参数4 ***/
    private CustomTextView param_4;
    /*** 参数5 ***/
    private CustomTextView param_5;
    /*** 投口标识 - 投口1 ***/
    private AppCompatButton setting_param_tk_1;
    /*** 投口标识 - 投口2 ***/
    private AppCompatButton setting_param_tk_2;
    /*** 投口标识 - 投口3 ***/
    private AppCompatButton setting_param_tk_3;
    /*** 投口标识 - 投口4 ***/
    private AppCompatButton setting_param_tk_4;
    /*** 投口标识 - 投口5 ***/
    private AppCompatButton setting_param_tk_5;

    private ArrayList<CustomTextView> paramListView = new ArrayList<>();

    // key 为投口地址； value 为 0 关，1 开
    private Map<String, String> map = new HashMap();

    private void init(Context context) {
        try {
            singletonSerl = SingletonSerl.getInstance();
        } catch (IOException e) {
            e.printStackTrace();
        }
        setClipChildren(false);
        LayoutInflater.from(context).inflate(R.layout.view_param_setting_term, this, true);
        param_setting_term_label = findViewById(R.id.param_setting_term_label);
        param_1 = findViewById(R.id.param_1);
        param_2 = findViewById(R.id.param_2);
        param_3 = findViewById(R.id.param_3);
        param_4 = findViewById(R.id.param_4);
        param_5 = findViewById(R.id.param_5);
        paramListView.add(param_1);
        paramListView.add(param_2);
        paramListView.add(param_3);
        paramListView.add(param_4);
        paramListView.add(param_5);
        setting_param_tk_1 = findViewById(R.id.setting_param_tk_1);
        setting_param_tk_2 = findViewById(R.id.setting_param_tk_2);
        setting_param_tk_3 = findViewById(R.id.setting_param_tk_3);
        setting_param_tk_4 = findViewById(R.id.setting_param_tk_4);
        setting_param_tk_5 = findViewById(R.id.setting_param_tk_5);
    }

    Handler mHandlerOpen = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (singletonSerl == null) {
                try {
                    singletonSerl = SingletonSerl.getInstance();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            LOG.e(TAG, String.format("%s号投口开始查询", "" + msg.what));
            switch (msg.what) {
                case 1:
                    ExecutorProcessPool.getInstance().execute(() -> {
                        boolean tk1 = open(SingletonSerl.byte_tk1, false);
                        LOG.e(TAG, "byte_tk1:" + tk1);
                        if (tk1) {
                            try {
                                SingletonSerl.getInstance().write(TAG, singletonSerl.deviceRunType(ByteUtil.hexByteToString(SingletonSerl.byte_tk1)));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            mHandlerOpen.sendEmptyMessageDelayed(1, 200);
                        }
                    });
                    break;
                case 2:
                    ExecutorProcessPool.getInstance().execute(() -> {
                        boolean tk2 = open(SingletonSerl.byte_tk2, false);
                        LOG.e(TAG, "byte_tk2:" + tk2);
                        if (tk2) {
                            try {
                                SingletonSerl.getInstance().write(TAG, singletonSerl.deviceRunType(ByteUtil.hexByteToString(SingletonSerl.byte_tk2)));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            mHandlerOpen.sendEmptyMessageDelayed(2, 200);
                        }
                    });
                    break;
                case 3:
                    ExecutorProcessPool.getInstance().execute(() -> {
                        boolean tk3 = open(SingletonSerl.byte_tk3, false);
                        LOG.e(TAG, "byte_tk3:" + tk3);
                        if (tk3) {
                            try {
                                SingletonSerl.getInstance().write(TAG, singletonSerl.deviceRunType(ByteUtil.hexByteToString(SingletonSerl.byte_tk3)));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            mHandlerOpen.sendEmptyMessageDelayed(3, 200);
                        }
                    });
                    break;
                case 4:
                    ExecutorProcessPool.getInstance().execute(() -> {
                        boolean tk4 = open(SingletonSerl.byte_tk4, false);
                        LOG.e(TAG, "byte_tk4:" + tk4);
                        if (tk4) {
                            try {
                                SingletonSerl.getInstance().write(TAG, singletonSerl.deviceRunType(ByteUtil.hexByteToString(SingletonSerl.byte_tk4)));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            mHandlerOpen.sendEmptyMessageDelayed(4, 200);
                        }
                    });
                    break;
                case 5:
                    ExecutorProcessPool.getInstance().execute(() -> {
                        boolean tk5 = open(SingletonSerl.byte_tk5, false);
                        LOG.e(TAG, "byte_tk5:" + tk5);
                        if (tk5) {
                            try {
                                SingletonSerl.getInstance().write(TAG, singletonSerl.deviceRunType(ByteUtil.hexByteToString(SingletonSerl.byte_tk5)));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            mHandlerOpen.sendEmptyMessageDelayed(5, 200);
                        }
                    });
                    break;
            }
        }
    };

    private void setOnClick() {
        setting_param_tk_1.setOnClickListener(view -> {
            boolean open = open(SingletonSerl.byte_tk1, true);
            setting_param_tk_1.setText("" + (open ? "1号停止" : "1号投口"));
            if (open) {
                mHandlerOpen.sendEmptyMessage(1);
            }
        });

        setting_param_tk_2.setOnClickListener(view -> {
            boolean open = open(SingletonSerl.byte_tk2, true);
            setting_param_tk_2.setText("" + (open ? "2号停止" : "2号投口"));
            if (open) {
                mHandlerOpen.sendEmptyMessage(2);
            }
        });

        setting_param_tk_3.setOnClickListener(view -> {
            boolean open = open(SingletonSerl.byte_tk3, true);
            setting_param_tk_3.setText("" + (open ? "3号停止" : "3号投口"));
            if (open) {
                mHandlerOpen.sendEmptyMessage(3);
            }
        });

        setting_param_tk_4.setOnClickListener(view -> {
            boolean open = open(SingletonSerl.byte_tk4, true);
            setting_param_tk_4.setText("" + (open ? "4号停止" : "4号投口"));
            if (open) {
                mHandlerOpen.sendEmptyMessage(4);
            }
        });

        setting_param_tk_5.setOnClickListener(view -> {
            boolean open = open(SingletonSerl.byte_tk5, true);
            setting_param_tk_5.setText("" + (open ? "5号停止" : "5号投口"));
            if (open) {
                mHandlerOpen.sendEmptyMessage(5);
            }
        });
    }

    public void onDestroy(){
        if(map!=null){
            map.clear();
        }
    }

    public boolean open(byte tkDz, boolean change) {
        String open_ = map.get(ByteUtil.hexByteToString(tkDz));
        if (change) {
            if (StringUtils.isEmpty(open_)) {
                // 首次打开
                open_ = "1";
            } else if (open_.equals("1")) {
                open_ = "0";
            } else {
                open_ = "1";
            }
            map.put(ByteUtil.hexByteToString(tkDz), open_);
        }
        return "1".equals(open_);
    }

    public void setLabel(String label) {
        if (TextUtils.isEmpty(label)) {
            return;
        }
        this.param_setting_term_label.setText(label);
    }

    /**
     * 设置参数标识
     *
     * @param label
     * @param key
     */
    public void setParamTag(String label, String key) {
        int index = 0;
        for (CustomTextView customTextView : this.paramListView) {
            customTextView.setParamTag(String.format("%s - 投口 - %s", label, index), String.format("%s_%s", key, index));
            index++;
        }
    }

    /**
     * 获取值
     *
     * @return
     */
    public ArrayList<HashMap<String, String>> getValue() {
        ArrayList<HashMap<String, String>> values = new ArrayList<>();
        for (CustomTextView customTextView : this.paramListView) {
            values.add(customTextView.getValueMap());
        }
        return values;
    }

    /**
     * 获取view
     *
     * @return
     */
    public LinkedList<CustomTextView> getView() {
        LinkedList<CustomTextView> values = new LinkedList<>();
        for (CustomTextView customTextView : this.paramListView) {
            values.add(customTextView);
        }
        return values;
    }

    public void setTkVisible(boolean visible) {
        this.setting_param_tk_1.setVisibility(visible ? VISIBLE : GONE);
        this.setting_param_tk_2.setVisibility(visible ? VISIBLE : GONE);
        this.setting_param_tk_3.setVisibility(visible ? VISIBLE : GONE);
        this.setting_param_tk_4.setVisibility(visible ? VISIBLE : GONE);
        this.setting_param_tk_5.setVisibility(visible ? VISIBLE : GONE);

        setOnClick();
    }


}
